package com.edu.controller;

import com.edu.dao.UserMapper;
import com.edu.data.User;
import com.edu.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    SqlSession sqlSession= MyBatisUtil.createSession();
    UserMapper userMapper=sqlSession.getMapper(UserMapper.class);

    @RequestMapping("/toUser")
    private void toUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("loginUser");
        if (user.getEuStatus() == 2) {// 如果是管理员登录
            List<User> users = userMapper.findByIdAll();
            req.setAttribute("users", users);
            req.getRequestDispatcher("../static/manage/user.jsp").forward(req, resp);
        } else if (user.getEuStatus() == 1) {// 如果是普通用户登录
            req.setAttribute("user", user);
            req.getRequestDispatcher("../static/manage/user.jsp").forward(req, resp);
        }
    }

    @RequestMapping("/readUser")
    private void readUser(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        String userId = request.getParameter("userId");
        User user = userMapper.findById(userId);
        String[] addr = user.getEuAddress().split(";");
        request.setAttribute("addr", addr);
        pupulateRequest(request, user);
        request.getRequestDispatcher("../static/manage/user-modify.jsp").forward(request, response);
    }

    @RequestMapping("/delUser")
    private void delUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        userMapper.delete(req.getParameter("userId"));
        resp.sendRedirect("toUser");
    }

    @RequestMapping("/modifyUser")
    private void modifyUser(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ParseException, ServletException, IOException {
        String entityId = req.getParameter("entityId");
        User user=userMapper.findById(entityId);
        populateEntity(req,user);
        userMapper.update(user,entityId);
        // 如果修改的是当前用户则改变session
        HttpSession session = req.getSession();
        User u = (User) session.getAttribute("loginUser");
        if (user.getEuUserId().equals(u.getEuUserId())) {
            session.setAttribute("loginUser", user);
        }
        resp.sendRedirect("toUser");
    }

    @RequestMapping("/toAddUser")
    private String toAddUser(){
        return "register";
    }

    @RequestMapping("/addUser")
    private String addUser(HttpServletRequest request){
        try {
            User user = new User();
            user.setEuStatus(1);
            user.setEuUserId(request.getParameter("userId"));
            user.setEuUserName(request.getParameter("userName"));
            user.setEuSex(request.getParameter("sex"));
            user.setEuPassword(request.getParameter("password"));
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date d = new java.sql.Date(simpleDateFormat.parse(request.getParameter("birthday").trim()).getTime());
            user.setEuBirthday(d.toString());
            user.setEuIdentityCode(request.getParameter("identityCode"));
            user.setEuEmail(request.getParameter("email"));
            user.setEuMobile(request.getParameter("mobile"));
            user.setEuAddress(request.getParameter("address"));
            userMapper.insert(user);
        } catch (Exception e) {
            Map<String, String> errors = new HashMap<String, String>();
            errors.put("userId", "用户名字已经存在");
        }
        request.setAttribute("msg", "已经成功注册请登录");
        return "login";
    }

    private void pupulateRequest(HttpServletRequest request, User user) {
        request.setAttribute("userId", user.getEuUserId());
        request.setAttribute("userName", user.getEuUserName());
        request.setAttribute("sex", user.getEuSex());
        request.setAttribute("password", user.getEuPassword());
        request.setAttribute("confirmPassword", user.getEuPassword());
        request.setAttribute("birthday", user.getEuBirthday());
        request.setAttribute("identityCode", user.getEuIdentityCode());
        request.setAttribute("email", user.getEuEmail());
        request.setAttribute("mobile", user.getEuMobile());
        request.setAttribute("address", user.getEuAddress());
    }

    private void populateEntity(HttpServletRequest request, User user) throws ParseException {
        user.setEuUserId(request.getParameter("userId"));
        user.setEuUserName(request.getParameter("userName"));
        user.setEuSex(request.getParameter("sex"));
        user.setEuPassword(request.getParameter("password"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new java.sql.Date(simpleDateFormat.parse(request.getParameter("birthday").trim()).getTime());
        user.setEuBirthday(d.toString());
        user.setEuIdentityCode(request.getParameter("identityCode"));
        user.setEuEmail(request.getParameter("email"));
        user.setEuMobile(request.getParameter("mobile"));
        String []addr=request.getParameterValues("address");
        StringBuffer b=new StringBuffer();
        for(int i=0;i<addr.length;i++){
            b.append(addr[i]);
            if(i!=addr.length-1)
                b.append(";");
        }
        user.setEuAddress(b.toString());
    }
}
